package top.kaoshanji.u2ch11c;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestTemplate;

import java.util.UUID;

/**
 * 代码清单-u2ch11c-231页a：应用程序的PaymentsProxy调用/createPayment端点
 * @author kaoshanji
 * ^_^
 * create time 2025/5/1 16:41
 */
@Component
public class PaymentsProxy {

    private final RestTemplate restTemplate;

    public PaymentsProxy(RestTemplate restTemplate) {
        this.restTemplate = restTemplate;
    }

    @Value("${payments.service.url}")
    private String paymentsServiceUrl;

    public Payment createPayment(Payment payment) {
        String uri = paymentsServiceUrl + "/createPayment";

        HttpHeaders httpHeaders = new HttpHeaders();
        httpHeaders.add("requestId", UUID.randomUUID().toString());

        HttpEntity<Payment> httpEntity = new HttpEntity<>(payment, httpHeaders);

        ResponseEntity<Payment> response = restTemplate.exchange(uri, HttpMethod.POST, httpEntity, Payment.class);

        return response.getBody();
    }


}
